/**
 * Copyright (c) 2010-2015 by skzr.org
 * All rights reserved.
 * @Author skzr.org(E-mail:skzr.org@gmail.com)
 * @date Feb 27, 2010 11:22:39 AM
 */
package org.skzr.framework.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.protocol.HTTP;

/**
 * for apache httpclient
 * @jdk 6.0
 * @author skzr.org(E-mail:skzr.org@gmail.com)
 * @version 1.0.1
 */
public class UtilHttpClient {
	private static String getHeaderValue(Header header) {
		return getHeaderValue(header, null);
	}
	private static String getHeaderValue(Header header, String name) {
		if (header == null) return null; 
		if (name == null || name.isEmpty()) return header.getValue();
		if (name.equals(header.getName())) return header.getValue();
		
		for(HeaderElement e : header.getElements()) {
			NameValuePair param = e.getParameterByName(name);
			if (param != null) return param.getValue();
		}
		return null;
	}
	private static String getContentCharSet(final HttpEntity entity) {
		assert entity != null;
		String ret = getHeaderValue(entity.getContentType(), "charset");
		return "GB2312".equalsIgnoreCase(ret) ? "GBK" : ret;
	}
	public static String toString(final HttpEntity entity) throws IOException {
		return toString(entity, null);
	}
	public static String toString(final HttpEntity entity, final String defaultCharset) throws IOException {
		assert entity != null;
        
        String charset = getContentCharSet(entity);
        if (charset == null) {
        	charset = defaultCharset;
        }
        if (charset == null) {
            charset = HTTP.DEFAULT_CONTENT_CHARSET;
        }
        String contentEncoding = getHeaderValue(entity.getContentEncoding());
        
        InputStream content = entity.getContent(), in = content;
        try {
	        if ("gzip".equalsIgnoreCase(contentEncoding)) {
	        	in = new GZIPInputStream(content);
	    	} else if (contentEncoding != null && contentEncoding.length() > 0) {
	    		throw new IllegalArgumentException("[待开发]目前不支持的内容编码:" + contentEncoding);
	    	}
	        return UtilIO.readText(in, entity.getContentLength(), charset);
        } finally {
        	UtilIO.close(in);
        	if (content != in) UtilIO.close(content);
        }
    }
}